<template>
  <div class="box-com">
    <h2>文章管理</h2>
    <el-form :inline="true" :model="formQuery" ref="queryFormRef">
      <el-form-item label="标题" prop="title">
        <el-input v-model="formQuery.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-select v-model="formQuery.categoryId" placeholder="请选择文章分类">
          <template v-for="item in cateGoryList" :key="item.id">
            <el-option :label="item.name" :value="item.id"></el-option>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="标签" prop="tagIds">
        <el-select multiple v-model="formQuery.tagIds" placeholder="请选择文章标签">
          <template v-for="item in tagList" :key="item.id">
            <el-option :label="item.name" :value="item.id"></el-option>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmitQuery">查询</el-button>
        <el-button type="default" @click="handleResetFeilds">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="post-list">
      <el-button type="primary" plain icon="el-icon-plus" @click="handleAddPost">添加文章</el-button>
      <el-table :data="postList" max-height="400">
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column prop="categoryId" label="分类" :formatter="formatterCategory"></el-table-column>
        <el-table-column prop="tagIds" label="标签" :formatter="formatterTag" min-width="180"></el-table-column>
        <el-table-column prop="lookCount" label="浏览数"></el-table-column>
        <el-table-column prop="likeCount" label="点赞数"></el-table-column>
        <el-table-column prop="collectCount" label="收藏数"></el-table-column>

        <el-table-column prop="createdAt" label="创建时间" :formatter="formatterDate" min-width="160"></el-table-column>
        <el-table-column label="操作" fixed="right" width="150px">
          <template #default="scope">
            <el-button type="text" @click="handleEditPost(scope.row)">编辑</el-button>
            <el-button type="text" @click="handleDeletePost(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="box-pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          :total="total"
          :page-sizes="[1, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, prev, pager, next, sizes,jumper"
        ></el-pagination>
      </div>
    </div>
    <!-- 新增文章 编辑文章面板 -->
    <right-panel v-model="panelVisible" :title="panelTitle" style="overflow-y:auto" :size="'85%'">
      <edit-post
        :type="editType"
        :data="editData"
        :cateGoryList="cateGoryList"
        :tagList="tagList"
        @submit="handleSubmitPost"
      />
    </right-panel>
  </div>
</template>
<script lang="ts">
import { computed, defineComponent, getCurrentInstance, onMounted, reactive, ref, watchEffect } from 'vue'
import { PostData, getPost, removePostByID, addNewPost, updatePostByID, PostAddData } from '@/api/post'
import EditPost from './component/editPost.vue'
import RightPanel from '@/components/RightPanel/index.vue'
import dayjs from 'dayjs'
import { ElForm } from 'element-plus'
import { CategoryAllList, getAllCategory } from '@/api/category'
import { getAllTag, TagAllList } from '@/api/tag'

type ElFormInstance = InstanceType<typeof ElForm>

export default defineComponent({
  name: 'Post',
  components: {
    RightPanel,
    EditPost
  },
  setup() {
    const { proxy } = getCurrentInstance()!
    const pageNum = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const panelVisible = ref(false)
    const queryFormRef = ref<ElFormInstance | null>(null)
    const cateGoryList = ref<CategoryAllList[]>([])
    const tagList = ref<TagAllList[]>([])
    const postList = ref<PostData[]>([])
    const editData = ref<PostAddData | null>(null)
    const editType = ref(1) // 0编辑 1新增
    const panelTitle = computed(() => editType.value === 1 ? '新增文章' : '编辑文章')
    const formQuery = reactive({
      title: '',
      categoryId: '',
      tagIds: []
    })
    const getPostList = () => {
      getPost({
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        ...formQuery
      }).then(res => {
        const { data } = res
        postList.value = data?.posts
        total.value = data?.total
      })
    }
    // 获取类目数据
    const getCategoryList = () => {
      getAllCategory().then(res => {
        const { data } = res
        cateGoryList.value = data
      })
    }
    // 获取标签数据
    const getTagList = () => {
      getAllTag().then(res => {
        tagList.value = res.data
      })
    }
    onMounted(() => {
      getCategoryList()
      getTagList()
    })
    // 自动追踪相关依赖属性变动获取数据
    watchEffect(() => {
      getPostList()
    })
    // 格式化日期
    const formatterDate = (row: PostData) => {
      return dayjs(row.createdAt).format('YYYY-MM-DD HH:mm:ss')
    }
    // 格式化分类
    const formatterCategory = (row: PostData) => {
      let str = ''
      cateGoryList.value.forEach(el => {
        if (el.id === Number(row.categoryId)) {
          str = el.name
        }
      })
      return str
    }
    // 格式化标签
    const formatterTag = (row: PostData) => {
      const ary: string[] = []
      row.tagIds.forEach(el => {
        tagList.value.forEach(tag => {
          if (el === tag.id) {
            ary.push(tag.name)
          }
        })
      })

      return ary.join(',')
    }
    // 查询
    const handleSubmitQuery = () => {
      getPostList()
    }
    // 重置
    const handleResetFeilds = () => {
      (queryFormRef.value as ElFormInstance).resetFields()
      getPostList()
    }
    // 分页
    const handleSizeChange = (val: number) => {
      pageSize.value = val
      getPostList()
    }
    const handleCurrentChange = (val: number) => {
      pageNum.value = val
      getPostList()
    }
    // 新增文章弹窗处理
    const handleAddPost = () => {
      editType.value = 1
      editData.value = {} as PostAddData
      panelVisible.value = true
    }
    // 编辑文章弹窗处理
    const handleEditPost = (row: PostAddData) => {
      editType.value = 0
      editData.value = { ...row }
      panelVisible.value = true
    }
    // 删除文章处理
    const handleDeletePost = (row: PostData) => {
      proxy?.$confirm(`您确认要删除文章${row.title}吗？`, '删除确认', {
        type: 'warning'
      }).then(() => {
        removePostByID(row.id).then(() => {
          proxy?.$message.success('文章删除成功')
          getPostList()
        }).catch(() => {
          proxy?.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      })
    }
    // 新增文章
    const addNewPostFun = (data: PostAddData) => {
      addNewPost(data).then(() => {
        proxy?.$message.success('文章添加成功')
        panelVisible.value = false
        getPostList()
      })
    }
    // 编辑文章
    const editPostFun = (data: PostAddData) => {
      updatePostByID(data.id, data).then(() => {
        proxy?.$message.success('文章编辑成功')
        panelVisible.value = false
        getPostList()
      })
    }
    // 提交新增文章信息
    const handleSubmitPost = (data: PostAddData) => {
      if (editType.value === 1) {
        addNewPostFun(data)// 新增
      } else if (editType.value === 0) {
        editPostFun(data)// 编辑
      }
    }
    return {
      pageNum,
      pageSize,
      total,
      formQuery,
      postList,
      editType,
      panelTitle,
      panelVisible,
      editData,
      cateGoryList,
      tagList,
      queryFormRef,
      handleAddPost,
      handleEditPost,
      handleDeletePost,
      addNewPostFun,
      editPostFun,
      handleSubmitPost,
      formatterDate,
      formatterTag,
      formatterCategory,
      handleSubmitQuery,
      handleResetFeilds,
      handleSizeChange,
      handleCurrentChange,
      getCategoryList
    }
  }
})
</script>

<style lang="scss" scoped>
</style>
